package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.mapper.UserInfoMapper;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    //    @Autowired
    //    为什么这个位置使用的是StringRedisTemplate 这个实现类进行注入呢？
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        String c = RandomUtil.randomNumbers(6);

        /*
           使用Session进行储存和校验
         *      String id = phone + "_code";
         *      session.setAttribute(id, c);
         *
         *
           使用Redis进行储存和校验
         *      使用层次感 对 key增加验证码有效期
                有个问题 我要是先发一条 然后刷新页面再发一条之前的能生效还是现在的能生效？
                只有最后一个生效 这边由于键是唯一的 所以最后一次的验证码才是最终的结果
         * */
        stringRedisTemplate.opsForValue().set(
                RedisConstants.LOGIN_CODE_KEY + phone,
                c, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
//        发送验证码!
        log.debug("发送短信验证码成功! code => {}", c);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误！");
        }
        /*
        *
        *       使用Session进行 校验
        //        最起码得是唯一标识
                String id = loginForm.getPhone() + "_code";
        //        这个位置进行校验
                String code = null;
                try {
                    code = (String) session.getAttribute(id);
                } catch (Exception e) {
                    return Result.fail("验证失败");
                }
                if (code == null || !code.equals(loginForm.getCode())) {
                    return Result.fail("验证失败!");
                }
        //        中间这个位置是查询用户 校验用户是否存在 存在就直接登录 不存在就直接创建用户

        //        储存用户信息的位置
        //        session.setAttribute("user", user);
        * */
//        验证码的获取和校验
        String code = (String) stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
        if (code == null || !code.equals(loginForm.getCode())) {
            return Result.fail("验证失败!");
        }

//        判断用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("phone", loginForm.getPhone());
//        QueryChainWrapper<User> phone = query().eq("phone", loginForm.getPhone());
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
//            没有 就进行创建
            user = createUserWithPhone(loginForm.getPhone());
        }
        /*
         *   将用户信息储存在redis中用于后续的认证操作
         * */

//      保存用户信息到redis
//      随机生成UUID 作为登录令牌

        String token = UUID.randomUUID().toString().replace("-", "");

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        /*
         *   储存以及设置有效期
         * */
        stringRedisTemplate.opsForHash().putAll(tokenKey, stringObjectMap);
        stringRedisTemplate.expire(tokenKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomNumbers(8));
        save(user);
        return user;
    }

    @Override
    public Result sign() {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请先登录");
        }
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        String yyyyMM = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + yyyyMM;
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请先登录");
        }
        Long userId = user.getId();
        LocalDateTime now = LocalDateTime.now();
        String yyyyMM = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + yyyyMM;
        int dayOfMonth = now.getDayOfMonth();
//        连续签到
        List<Long> list = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().get(
                                BitFieldSubCommands
                                        .BitFieldType
                                        .unsigned(dayOfMonth))
                        .valueAt(0));

        if (list == null || list.isEmpty()) {
            return Result.ok();
        }
        Long num = list.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }

        int count = 0;
        while (true) {
            if ((num & 1) == 0) {
                break;
            } else {
                count++;
                num >>>= 1;
            }
        }
        return Result.ok(count);
    }
}
